package com.blacktech.dbu.meta.service;

import com.blacktech.dbu.core.exception.BusinessException;
import com.blacktech.dbu.core.response.ResponseCode;
import com.blacktech.dbu.meta.entity.DbuProduct;
import com.blacktech.dbu.meta.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 产品管理服务
 *
 * @author Yanyunsong
 */
@Service
@Transactional
public class ProductService {

    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    /**
     * 创建产品
     */
    public DbuProduct createProduct(DbuProduct product) {
        // 验证产品代号是否已存在
        if (productRepository.existsByProductCodeIgnoreCase(product.getProductCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(),
                "产品代号 '" + product.getProductCode() + "' 已存在");
        }

        // 验证必填字段
        validateProduct(product);

        return productRepository.save(product);
    }

    /**
     * 更新产品
     */
    public DbuProduct updateProduct(Long id, DbuProduct product) {
        Optional<DbuProduct> existingProductOpt = productRepository.findById(id);
        if (existingProductOpt.isEmpty()) {
            return null;
        }

        DbuProduct existingProduct = existingProductOpt.get();

        // 如果产品代号发生变化，检查新代号是否已存在
        if (!existingProduct.getProductCode().equals(product.getProductCode()) &&
            productRepository.existsByProductCodeIgnoreCase(product.getProductCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(),
                "产品代号 '" + product.getProductCode() + "' 已存在");
        }

        // 更新字段
        updateProductFields(existingProduct, product);

        return productRepository.save(existingProduct);
    }


    /**
     * 批量删除产品
     */
    @Transactional
    public int batchDeleteProducts(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }

        // 检查是否有关联的数据，如schema等
        for (Long id : ids) {
            if (!productRepository.existsById(id)) {
                throw new BusinessException(ResponseCode.NOT_FOUND.getCode(),
                    "产品ID " + id + " 不存在");
            }
        }

        // 执行删除
        productRepository.deleteAllById(ids);
        return ids.size();
    }

    /**
     * 验证产品信息
     */
    private void validateProduct(DbuProduct product) {
        if (product.getProductCode() == null || product.getProductCode().trim().isEmpty()) {
            throw new BusinessException(ResponseCode.BAD_REQUEST.getCode(), "产品代号不能为空");
        }

        if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
            throw new BusinessException(ResponseCode.BAD_REQUEST.getCode(), "产品名称不能为空");
        }

        // 产品代号长度限制
        if (product.getProductCode().length() > 50) {
            throw new BusinessException(ResponseCode.BAD_REQUEST.getCode(), "产品代号长度不能超过50个字符");
        }

        // 产品名称长度限制
        if (product.getProductName().length() > 100) {
            throw new BusinessException(ResponseCode.BAD_REQUEST.getCode(), "产品名称长度不能超过100个字符");
        }

        // 产品描述长度限制
        if (product.getProductDesc() != null && product.getProductDesc().length() > 500) {
            throw new BusinessException(ResponseCode.BAD_REQUEST.getCode(), "产品描述长度不能超过500个字符");
        }
    }

    /**
     * 更新产品字段
     */
    private void updateProductFields(DbuProduct existingProduct, DbuProduct updateProduct) {
        if (updateProduct.getProductCode() != null) {
            existingProduct.setProductCode(updateProduct.getProductCode());
        }

        if (updateProduct.getProductName() != null) {
            existingProduct.setProductName(updateProduct.getProductName());
        }

        if (updateProduct.getProductDesc() != null) {
            existingProduct.setProductDesc(updateProduct.getProductDesc());
        }

        // 注意：这里不更新ID和创建时间等系统字段
    }
}